<template>
  <a-modal
    :maskClosable="maskClosable"
    title="添加IT设备"
    :width="600"
    :visible="visible"
    :confirm-loading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" :labelCol="labelCol" :wrapperCol="wrapperCol">
        <a-form-item label="设备类型">
          <a-select
            :getPopupContainer="
                triggerNode => {
                  return triggerNode.parentNode || document.body;
                }"
            v-model="type">
            <a-select-option v-for="t in typeData" :key="t.id">{{ t.name }}</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="数据中心">
          <a-select 
            :getPopupContainer="
              triggerNode => {
                return triggerNode.parentNode || document.body;
              }"
            v-decorator="['datacenterId',{rules:[
              {required:true,message:'数据中心不能为空',},
              ]}]"
            @change="loadCabinetList"
          >
            <a-select-option v-for="d in datacenterList" :key="d.id">{{ d.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="机柜">
          <a-select 
            :getPopupContainer="
              triggerNode => {
                return triggerNode.parentNode || document.body;
              }"
            v-decorator="['cabinetId',{rules:[
              {required:true,message:'机柜不能为空',},
              ]}]">
            <a-select-option v-for="d in cabinetList" :key="d.id">{{ d.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="设备名称">
          <a-input autocomplete="off" v-decorator="['name',{rules:[
              {required:true,message:'设备名称不能为空',},
              { validator: validators.noWhitespace(), },
              { validator: validators.noIllegalString() },
              {max:10,message:'长度在 1 到 10 个字符', trigger: 'blur'},
              ]}]"/>
        </a-form-item>
        <a-form-item label="设备识别号">
          <a-input autocomplete="off" v-decorator="['esn',{rules:[
              {required:true,message:'设备识别号不能为空',},
              { validator: validators.noWhitespace(), },
              { validator: validators.noIllegalString() },
              {max:10,message:'长度在 1 到 10 个字符', trigger: 'blur'},
              ]}]"/>
        </a-form-item>
        <a-form-item label="设备型号">
          <a-input autocomplete="off" v-decorator="['deviceModel',{rules:[
              {required:true,message:'设备型号不能为空',},
              { validator: validators.noWhitespace(), },
              { validator: validators.noIllegalString() },
              {max:10,message:'长度在 1 到 10 个字符', trigger: 'blur'},
              ]}]"/>
        </a-form-item>
        <a-form-item label="设备厂商">
          <a-input autocomplete="off" v-decorator="['deviceManufacturer',{rules:[
              {required:true,message:'设备厂商不能为空',},
              { validator: validators.noWhitespace(), },
              { validator: validators.noIllegalString() },
              {max:10,message:'长度在 1 到 10 个字符', trigger: 'blur'},
              ]}]"/>
        </a-form-item>

        <div v-if="type==='node'">
          <a-form-item label="管理网IP">
            <a-input autocomplete="off" v-decorator="['node.mgmIp',{rules:[
                {required:true,message:'管理网IP不能为空',},
                { validator: this.validators.noWhitespace(), },
                { validator: this.validators.isValidIp(), },
                ]}]"/>
          </a-form-item>
          <a-form-item label="带外管理IP">
            <a-input autocomplete="off" v-decorator="['node.ipmiIp',{rules:[
                {required:true,message:'带外管理IP不能为空',},
                { validator: this.validators.noWhitespace(), },
                { validator: this.validators.isValidIp(), },
                ]}]"/>
          </a-form-item>
          <a-form-item label="带外管理用户">
            <a-input autocomplete="off" v-decorator="['node.ipmiUser',{rules:[
                {required:true,message:'带外管理用户不能为空',},
                { validator: validators.noWhitespace(), },
                { validator: validators.noIllegalString() },
                {max:10,message:'长度在 1 到 10 个字符', trigger: 'blur'},
                ]}]"/>
          </a-form-item>
          <a-form-item v-if="visible" label="带外管理密码">
            <a-input-password autocomplete="new-password" v-decorator="['node.ipmiPassword',{rules:[
                {required:true,message:'带外管理密码不能为空',},
                { validator: validators.noWhitespace(), },
                { validator: validators.enName(), },
                { validator: validators.noIllegalString(), },
                {min:6,message:'带外管理密码长度不能小于6'},
                {max:20,message:'带外管理密码长度不能大于20'},
                ]}]"/>
          </a-form-item>
          <a-form-item label="主机名">
            <a-input autocomplete="off" v-decorator="['node.hostname',{rules:[
                {required:true,message:'主机名不能为空',},
                { validator: validators.noWhitespace(), },
                { validator: validators.noIllegalString() },
                {max:10,message:'长度在 1 到 10 个字符', trigger: 'blur'},
                ]}]"/>
          </a-form-item>
          <a-form-item label="额定电压">
            <a-input autocomplete="off" :max-length="7" addon-after="V" @keyup="clearNoNum('node.ratedVoltageSm')" @blur="clearNoNum('node.ratedVoltageSm')" v-decorator="['node.ratedVoltageSm',{rules:[
                {required:true,message:'额定电压不能为空',},
                { validator: validators.xmax({max:9999}), trigger: 'blur', },
                { validator: validators.xmin({min:0}), trigger: 'blur', },
                ]}]"/>
          </a-form-item>
          <a-form-item label="额定功率">
            <a-input autocomplete="off" :max-length="7" addon-after="W" @keyup="clearNoNum('node.ratedPowerSm')" @blur="clearNoNum('node.ratedPowerSm')" v-decorator="['node.ratedPowerSm',{rules:[
                {required:true,message:'额定功率不能为空',},
                { validator: validators.xmax({max:9999}), trigger: 'blur', },
                { validator: validators.xmin({min:0}), trigger: 'blur', },
                ]}]"/>
          </a-form-item>
        </div>
        <div v-if="type==='switcher'">
          <a-form-item label="交换机IP">
            <a-input autocomplete="off" v-decorator="['switcher.ip',{rules:[
                {required:true,message:'交换机IP不能为空',},
                { validator: this.validators.noWhitespace(), },
                { validator: this.validators.isValidIp(), },
                ]}]"/>
          </a-form-item>
          <a-form-item label="交换机Community">
            <a-input autocomplete="off" v-decorator="['switcher.community',{rules:[
                {required:true,message:'交换机Community不能为空',},
                { validator: validators.noWhitespace(), },
                { validator: validators.noIllegalString() },
                {max:10,message:'长度在 1 到 10 个字符', trigger: 'blur'},
                ]}]"/>
          </a-form-item>
        </div>
      </a-form>
    </a-spin>
  </a-modal>
</template>
<script>
import { gPostAction } from '@/api/manage'
import { sm4Encrypt, randomString } from "@/utils/sm4"
import { sm3Hash } from "@/utils/sm3"
import { SM4_KEY } from "@/store/mutation-types"
import { filterToFloat } from "@/utils/util";
export default {
  name: 'AddModal',
  data() {
    return {
      visible: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      model: {},
      typeData:[
        {
          id:'node',
          name:'服务器'
        },
        {
          id:'switcher',
          name: '交换机'
        }
      ],
      type: 'node',
      datacenterList: [],
      cabinetList: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      url: {
        datacenterPage: '/asset/pageDatacenter',
        cabinetPage: '/asset/pageDevice',
      },
      maskClosable: false,
    }
  },
  methods: {
    clearNoNum(fieldName) {
      let obj = {}
      obj[fieldName] = filterToFloat(this.form.getFieldValue(fieldName))
      this.form.setFieldsValue(obj);
      this.form.validateFields([fieldName], (errors, values) => {});
    },
    loadDatacenterList() {
      gPostAction(this.url.datacenterPage, {}).then((res) => {
        this.datacenterList = res.data.list
        // if (this.datacenterList.length) {
        //   this.node.datacenterId = this.datacenterList[0].id
        //   this.switcher.datacenterId =this.datacenterList[0].id
        // }
      })
    },
    loadCabinetList(val) {
      this.form.setFieldsValue({
        cabinetId: undefined,
      });
      this.cabinetList = [];
      let requestData = {
        pageSize: 999,
        pageNo: 1,
        type: 5,
        datacenterId: val,
      };
      gPostAction(this.url.cabinetPage, requestData).then((res) => {
        this.cabinetList = res.data.list
        // if (this.datacenterList.length) {
        //   this.node.datacenterId = this.datacenterList[0].id
        //   this.switcher.datacenterId =this.datacenterList[0].id
        // }
      })
    },
    add(type) {
      this.visible = true
      this.$nextTick(() => {
        this.form.resetFields()
        // Object.keys(this.node).forEach(key=>this.node[key]='')
        // Object.keys(this.switcher).forEach(key=>this.switcher[key]='')
        this.loadDatacenterList()
      })
      // this.model = Object.assign({}, record)
    },
    handleOk(e) {
      this.form.validateFields((err,values)=>{
        if (!err) {
          this.confirmLoading = true
          this.$ls.set(SM4_KEY, randomString());
          if (this.type==='node'){
            this.nodeOk(values)
          }
          else if (this.type==='switcher'){
            this.switcherOk(values)
          }
        }
      })
    },
    nodeOk(values){
      // const sm4 = require('sm-crypto').sm4
      let ipmiPassword = values.node.ipmiPassword;
      let ratedVoltageSm = parseFloat(values.node.ratedVoltageSm) + '';
      let ratedPowerSm = parseFloat(values.node.ratedPowerSm) + '';
      const postData = {
        datacenterId: values.datacenterId,
        cabinetId: values.cabinetId,
        name:values.name,
        deviceManufacturer:values.deviceManufacturer,
        deviceModel:values.deviceModel,
        esn:values.esn,
        hostname:values.node.hostname,
        ipmiIp:values.node.ipmiIp,
        // ipmiPassword: sm4Encrypt(ipmiPassword + sm3Hash(ipmiPassword)),
        ipmiUser: values.node.ipmiUser,
        mgmIp: values.node.mgmIp,
        title: "精确管控与供电制冷联动-基础资源细粒度感知-资源管理-L2层：IT设备"
        // ratedVoltageSm: sm4Encrypt(ratedVoltageSm + sm3Hash(ratedVoltageSm)),
        // ratedPowerSm: sm4Encrypt(ratedPowerSm + sm3Hash(ratedPowerSm)),
      }

      let valStr = ipmiPassword + '|' + ratedPowerSm + '|' + ratedVoltageSm;
      let sm3Str = sm3Hash(valStr);
      postData.smData = sm4Encrypt(valStr + sm3Str);

      gPostAction('/asset/createNode', postData)
        .then((res) => {
          if (res.success) {
            this.$message.success('操作成功')
            this.$emit("ok",'node')
          }
        })
        .finally(() => {
          this.confirmLoading = false
          this.handleCancel()
        })
    },
    switcherOk(values){
      // const sm4 = require('sm-crypto').sm4
      let str = values.switcher.community;
      const postData = {
        datacenterId: values.datacenterId,
        cabinetId: values.cabinetId,
        name: values.name,
        deviceManufacturer:values.deviceManufacturer,
        deviceModel:values.deviceModel,
        esn:values.esn,
        community:sm4Encrypt(str + sm3Hash(str)),
        ip:values.switcher.ip,
        title: "精确管控与供电制冷联动-基础资源细粒度感知-资源管理-L2层：IT设备"
      }

      gPostAction('/asset/createSwitcher', postData)
        .then((res) => {
          if (res.success) {
            this.$message.success('操作成功')
            this.$emit("ok",'switcher')
          }
        })
        .finally(() => {
          this.confirmLoading = false
          this.handleCancel()
        })
    },
    handleCancel(e) {
      this.visible = false
    },
  },
}
</script>
